package model;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Parsing file
 * Handler needed to extract data from XML-file
@Annot(author="maxim", description = "Handler needed to extract data from XML-file")
*/
public class MyHandler extends DefaultHandler{
	private Storage storage;
	private String temp;
	private WorkArea workarea;
	static List<Storage> storages = new ArrayList<Storage>();
	List<WorkArea> works = new ArrayList<WorkArea>();
	Random r = new Random();
	/**
	 * Receive notification of the start of an element
	 * @Annot(author="maxim", description = "Receive notification of the start of an element")
	 */
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		temp = "";
		if (qName.equalsIgnoreCase("WorkArea")) {
			workarea = new WorkArea();
			works.add(workarea);
			}
		
		
		if (qName.equalsIgnoreCase("Storage")) {
			storage = new Storage();			
			}
	}

	/**
	 * Receive notification of the end of an element
	 * @Annot(author="maxim", description = " Receive notification of the end of an element")
	 */
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {

		if (qName.equalsIgnoreCase("STORAGE")) {
			storages.add(storage);
			
		}
		if (qName.equalsIgnoreCase("NAME")) {
			if (temp.contains("Distribution area")) {
				workarea.setName(temp);
				workarea.setId(r.nextInt(20));
			} else {
				storage.setName(temp);		
				
				storage.setId(r.nextInt(20));
				storage.setWorkAreaId(workarea.getId());
			}
		} else if (qName.equalsIgnoreCase("WEIGHT")) {
			int temp1 = Integer.parseInt(temp);
			storage.setWeight(temp1);			
		} else if (qName.equalsIgnoreCase("X")) {
			int temp1 = Integer.parseInt(temp);
			storage.setX(temp1);
		} else if (qName.equalsIgnoreCase("Y")) {
			int temp1 = Integer.parseInt(temp);
			storage.setY(temp1);
		}
	}
/**
 * Receive notification of character data inside an element
 * @Annot(author="maxim", description = "Receive notification of character data inside an element")
 */
	@Override
	public void characters(char[] buffer, int start, int length)
			throws SAXException {
		temp = new String(buffer, start, length);
	}
	

	/**
	 * Return List<Storage>
	 * @Annot(author="maxim", description = "Return List<Storage>")
	 * @return
	 */
	public List<Storage> getStore() {
		return storages;
	}
	/**
	 * Return List<WorkArea>
	 * @Annot(author="maxim", description = "Return List<WorkArea>")
	 * @return
	 */
	public List<WorkArea> getWork() {
		return works;
	}


}
